package com.crm.system.service.impl.returnMoney;

import com.crm.common.model.DataResponse;
import com.crm.common.model.DhPageInfo;
import com.crm.common.model.DhResponse;
import com.crm.common.model.Enum.ResponseCodeEnum;
import com.crm.common.util.CommonUtils;
import com.crm.common.util.DateUtil;
import com.crm.common.util.fastdfs.FastDFSClient;
import com.crm.dao.mapper.customMapper.returnMoneyManagerCustomMapper.BankOrderCustomMapper;
import com.crm.model.entity.contractManager.CustomerContract;
import com.crm.model.entity.finishOrderProduct.FinishOrderProduct;
import com.crm.model.entity.orderManager.CustomerProductOrder;
import com.crm.model.entity.returnMoney.*;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.qo.messageManager.MessageAddQO;
import com.crm.model.qo.returnMoney.ReturnMoneyExamineQO;
import com.crm.model.vo.customerContractManager.CustomerContractDetailVO;
import com.crm.model.vo.finishOrderProduct.FinishOrderProductVO;
import com.crm.model.vo.returnMoney.FinanceProductOderInfoVO;
import com.crm.model.vo.returnMoney.ReturnMoneyExamineVO;
import com.crm.model.vo.returnMoney.ReturnMoneyVO;
import com.crm.service.contractManager.CustomerContractDbService;
import com.crm.service.finishOrderProductManager.FinishOrderProductDbService;
import com.crm.service.orderManager.CustomerProductOrderDbService;
import com.crm.service.returnMoney.*;
import com.crm.service.sys.UserAccountDbService;
import com.crm.system.service.FileUploadService;
import com.crm.system.service.contractManager.CustomerContractService;
import com.crm.system.service.messageManager.MessageService;
import com.crm.system.service.returnMoney.BankFlowExamineService;
import com.crm.system.service.returnMoney.ReturnMoneyExamineService;
import com.crm.system.service.returnMoney.ReturnMoneyService;
import com.crm.system.service.returnMoney.RmExamineRecordService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

@Service
@Slf4j
public class ReturnMoneyExamineServiceImpl implements ReturnMoneyExamineService {

    @Autowired
    private com.crm.service.returnMoney.ReturnMoneyExamineDbService returnMoneyExamineDbService;
    @Autowired
    private BankFlowDbService bankFlowDbService;
    @Autowired
    private ReturnMoneyDbservice returnMoneyDbservice;
    @Autowired
    private FinishOrderProductDbService finishOrderProductDbService;
    @Autowired
    private CustomerProductOrderDbService customerProductOrderDbService;
    @Autowired
    private CustomerContractDbService customerContractDbService;
    @Autowired
    private ReturnMoneyService returnMoneyService;
    @Autowired
    private BankOrderCustomMapper bankOrderCustomMapper;
    @Autowired
    private BankFlowExamineService bankFlowExamineService;
    @Autowired
    private ReturnMoneyLogDbService returnMoneyLogDbService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private UserAccountDbService userAccountDbService;
    @Autowired
    private FileUploadService fileUploadService;
    private FastDFSClient fastDFSClient = new FastDFSClient();
    @Autowired
    private CustomerContractService customerContractService;
    @Autowired
    private RmExamineRecordDbService rmExamineRecordDbService;

    @Override
    public DhPageInfo<ReturnMoneyExamineVO> selectPageList(Integer pageIndex, Integer pageSize, ReturnMoneyExamineQO returnMoneyExamineQO) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

//        UserAccount curUserAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
//
//        if(!"3".equals(curUserAccount.getDeptId())){
//            returnMoneyExamineQO.setCompanyId(curUserAccount.getCompanyId());
//        }

        Integer dateUnit = 0;
        if (StringUtils.isNotBlank(returnMoneyExamineQO.getDateType())) {
            if ("thisWeek".equals(returnMoneyExamineQO.getDateType())) {
                //本周
                dateUnit = 1;
            }
            if ("thisMonth".equals(returnMoneyExamineQO.getDateType())) {
                //本月
                dateUnit = 2;
            }
            if ("day".equals(returnMoneyExamineQO.getDateType())) {
                //今天
                dateUnit = 3;
            }
        }

        returnMoneyExamineQO.setDateUnit(dateUnit);
        List<ReturnMoneyExamineVO> list = returnMoneyExamineDbService.selectList(returnMoneyExamineQO);
        PageInfo<ReturnMoneyExamineVO> pageInfo=new PageInfo<>(list);
        return new DhPageInfo<ReturnMoneyExamineVO>(pageInfo,list);
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public synchronized DataResponse examine(ReturnMoneyExamine returnMoneyExamine) {
        if(StringUtils.isBlank(returnMoneyExamine.getExamineId())){
            return new DhResponse(ResponseCodeEnum.PARAMETER_ERROR.getResponseCode());
        }
        ReturnMoneyExamine oldExamine = returnMoneyExamineDbService.selectByPrimaryKey(returnMoneyExamine.getExamineId());
        if(oldExamine == null || (oldExamine.getDeleteStatus() != null && oldExamine.getDeleteStatus() == 1)){
            return new DhResponse(ResponseCodeEnum.RETURN_MONEY_EXAMINE_NOT_EXIST.getResponseCode());
        }
        //总审核状态，0：客服正在审核，1：财务正在审核，2：审核通过，3：审核未通过
        if(oldExamine.getExamineState() == 2){
            return new DhResponse(ResponseCodeEnum.RETURN_MONEY_EXAMINE_FAIL_2.getResponseCode());
        }
        if(oldExamine.getExamineState() == 3){
            return new DhResponse(ResponseCodeEnum.RETURN_MONEY_EXAMINE_FAIL_3.getResponseCode());
        }

        UserAccount curUserAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        //部门id  3:总部财务;4:分公司财务;5:分总;6:客服;7:销总;8:网络部
        String deptId = curUserAccount.getDeptId();

        if(oldExamine.getExamineState() == 0){//客服正在审核
            if(oldExamine.getCsExamineState() == 3){
                return new DhResponse(ResponseCodeEnum.RETURN_MONEY_EXAMINE_FAIL_UPLOAD_FILE.getResponseCode());
            }
            if (!"6".equals(deptId)){
                return new DhResponse(ResponseCodeEnum.RETURN_MONEY_EXAMINE_FAIL_CUR_IS_CS.getResponseCode());
            }
            if(returnMoneyExamine.getCsExamineState() == null){
                return new DhResponse(ResponseCodeEnum.PARAMETER_ERROR.getResponseCode());
            }
            if(!new ArrayList<Short>(Arrays.asList(new Short[]{0, 1, 2, 3})).contains(returnMoneyExamine.getCsExamineState())){
                return new DhResponse(ResponseCodeEnum.PARAMETER_ERROR.getResponseCode());
            }
            returnMoneyExamine.setFinanceExamineState(null);
            returnMoneyExamine.setFinanceExamineRemark(null);
        }else{//财务正在审核
            if(oldExamine.getFinanceExamineState() == 3){
                return new DhResponse(ResponseCodeEnum.RETURN_MONEY_EXAMINE_FAIL_UPLOAD_FILE.getResponseCode());
            }
            //3是总部财务，4是分公司财务
            if (!"3".equals(deptId) && !"4".equals(deptId)){
                return new DhResponse(ResponseCodeEnum.RETURN_MONEY_EXAMINE_FAIL_CUR_IS_FINANCE.getResponseCode());
            }
            if (!"3".equals(deptId)){
                return new DhResponse(ResponseCodeEnum.NO_AUTH.getResponseCode());
            }
            if(returnMoneyExamine.getFinanceExamineState() == null){
                return new DhResponse(ResponseCodeEnum.PARAMETER_ERROR.getResponseCode());
            }
            if(!new ArrayList<Short>(Arrays.asList(new Short[]{0, 1, 2, 3})).contains(returnMoneyExamine.getFinanceExamineState())){
                return new DhResponse(ResponseCodeEnum.PARAMETER_ERROR.getResponseCode());
            }
            //审核失败：客服审核不通过，财务不能审核通过
            if(oldExamine.getCsExamineState() == 2 && returnMoneyExamine.getFinanceExamineState() == 1){
                return new DhResponse(ResponseCodeEnum.RETURN_MONEY_EXAMINE_FAIL_CS_REJECT.getResponseCode());
            }
            returnMoneyExamine.setCsExamineState(null);
            returnMoneyExamine.setCsExamineRemark(null);
        }
        //总审核状态不允许页面修改
        returnMoneyExamine.setExamineState(null);
        if(returnMoneyExamine.getCsExamineRemark() != null && returnMoneyExamine.getCsExamineRemark().length() > 300){
            returnMoneyExamine.setCsExamineRemark(returnMoneyExamine.getCsExamineRemark().substring(0,300));
        }
        if(returnMoneyExamine.getFinanceExamineRemark() != null && returnMoneyExamine.getFinanceExamineRemark().length() > 300){
            returnMoneyExamine.setFinanceExamineRemark(returnMoneyExamine.getFinanceExamineRemark().substring(0,300));
        }

        boolean sendMsg = false;
        Date now = new Date();
        if(oldExamine.getExamineState() == 0) {//客服正在审核
            returnMoneyExamine.setCsExaminePeopleId(curUserAccount.getAccountId());
            returnMoneyExamine.setCsExamineTime(now);
            if(returnMoneyExamine.getCsExamineState() == 1 || returnMoneyExamine.getCsExamineState() == 2){//审核通过或不通过
                //当前审核人更换为财务
                returnMoneyExamine.setExamineState((short) 1);
                //财务审核状态改为正在审核
                returnMoneyExamine.setFinanceExamineState((short) 0);
                //清空财务审核备注
                returnMoneyExamine.setFinanceExamineRemark("");
            }
            sendMsg = true;
        }else{
            if(returnMoneyExamine.getFinanceExamineState() == 1 || returnMoneyExamine.getFinanceExamineState() == 2){//审核通过或不通过
                return this.finalExamine(returnMoneyExamine, oldExamine);
            }else if(returnMoneyExamine.getFinanceExamineState() == 3){//补充材料
                returnMoneyExamine.setFinanceExaminePeopleId(curUserAccount.getAccountId());
                returnMoneyExamine.setFinanceExamineTime(now);
                sendMsg = true;
            }
        }
        if(sendMsg){//给业务人员发送站内信
            //产品订单
            CustomerProductOrder oldCustomerProductOrder = customerProductOrderDbService.selectCustomerProductOrderById(oldExamine.getProductOrderId());
            //回款记录
            ReturnMoneyVO oldReturnMoney = returnMoneyDbservice.getReturnMoenyInfoById(oldExamine.getReturnMoneyId());
            if(oldExamine.getExamineState() == 0) {//客服正在审核
                this.sendMsg(returnMoneyExamine.getExamineId(), oldExamine.getExamineState(), returnMoneyExamine.getCsExamineState(), oldCustomerProductOrder, oldReturnMoney);
            }else{
                this.sendMsg(returnMoneyExamine.getExamineId(), oldExamine.getExamineState(), returnMoneyExamine.getFinanceExamineState(), oldCustomerProductOrder, oldReturnMoney);
            }
        }

        RmExamineRecord examineRecord = new RmExamineRecord();
        examineRecord.setRecordId(CommonUtils.getGUID());
        examineRecord.setExamineId(returnMoneyExamine.getExamineId());
        examineRecord.setCompanyId(curUserAccount.getCompanyId());
        examineRecord.setExaminePeopleId(curUserAccount.getAccountId());
        examineRecord.setExamineTime(now);
        if(oldExamine.getExamineState() == 0) {//客服正在审核
            examineRecord.setExaminePeopleType((short) 1);
            examineRecord.setExamineRemark(returnMoneyExamine.getCsExamineRemark());
            examineRecord.setExamineState(returnMoneyExamine.getCsExamineState());
        }else{
            examineRecord.setExaminePeopleType((short) 2);
            examineRecord.setExamineRemark(returnMoneyExamine.getFinanceExamineRemark());
            examineRecord.setExamineState(returnMoneyExamine.getFinanceExamineState());
        }
        //保存审核记录
        rmExamineRecordDbService.insertSelective(examineRecord);

        returnMoneyExamine.setLastRecordId(examineRecord.getRecordId());
        returnMoneyExamineDbService.updateByPrimaryKeySelective(returnMoneyExamine);
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public synchronized DataResponse finalExamine(ReturnMoneyExamine returnMoneyExamine, ReturnMoneyExamine oldExamine) {
        //银行流水记录id
        String flowId = oldExamine.getFlowId();
        //原银行流水记录
        BankFlow oldBankFlow = bankFlowDbService.selectByFlowId(flowId);
//        if(oldBankFlow == null){
//            log.error("预回款审核时找不到流水记录");
//            return new DhResponse(ResponseCodeEnum.BUSINESS_ERROR.getResponseCode());
//        }
        //回款id
        String returnMoneyId = oldExamine.getReturnMoneyId();
//        if(StringUtils.isBlank(returnMoneyId)){
//            log.error("预回款审核时找不到回款id");
//            return new DhResponse(ResponseCodeEnum.BUSINESS_ERROR.getResponseCode());
//        }
        //原回款记录
        ReturnMoneyVO oldReturnMoney = returnMoneyDbservice.getReturnMoenyInfoById(returnMoneyId);
//        if(oldReturnMoney == null){
//            log.error("预回款审核时找不到回款记录");
//            return new DhResponse(ResponseCodeEnum.BUSINESS_ERROR.getResponseCode());
//        }

        //订单id
        String productOrderId = oldExamine.getProductOrderId();
//        if(StringUtils.isBlank(productOrderId)){
//            log.error("预回款审核时找不到订单id");
//            return new DhResponse(ResponseCodeEnum.BUSINESS_ERROR.getResponseCode());
//        }

        //到款金额
        BigDecimal arriveMoney = (oldReturnMoney==null || oldReturnMoney.getArriveMoney()==null) ? new BigDecimal("0") : oldReturnMoney.getArriveMoney();

        //产品号
        String finishOrderProductNum = oldExamine.getFinishOrderProductNum();
        FinishOrderProductVO oldFinishOrderProduct = finishOrderProductDbService.selectFinishOrderProductByNumber(finishOrderProductNum);
        //产品订单
        CustomerProductOrder oldCustomerProductOrder = customerProductOrderDbService.selectCustomerProductOrderById(productOrderId);

        UserAccount curUserAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        Date now = new Date();

        //预回款审核不通过，先修改银行流水的可用金额、已用金额、关联状态，删除回款记录
        if(returnMoneyExamine.getFinanceExamineState() == 2) {
            if(StringUtils.isNoneBlank(returnMoneyId)) {
                if (oldReturnMoney != null && oldBankFlow != null) {
                    //贷方金额
                    BigDecimal creditMoney = oldBankFlow.getCreditMoney() == null ? new BigDecimal("0") : oldBankFlow.getCreditMoney();
                    //可用金额
                    BigDecimal availableAmount = oldBankFlow.getAvailableAmount() == null ? new BigDecimal("0") : oldBankFlow.getAvailableAmount();
                    //已用金额
                    BigDecimal usedAmount = oldBankFlow.getUsedAmount() == null ? new BigDecimal("0") : oldBankFlow.getUsedAmount();
                    //可用金额加到款金额
                    availableAmount = availableAmount.add(arriveMoney);
                    //已用金额减到款金额
                    usedAmount = usedAmount.subtract(arriveMoney);

                    BankFlow bf = new BankFlow();
                    bf.setFlowId(flowId);
                    bf.setUpdateTime(now);
                    bf.setAvailableAmount(availableAmount);
                    bf.setUsedAmount(usedAmount);
                    //若贷方金额等于可用金额，关联状态改为N未关联，否则改为B部分关联
                    if (creditMoney.compareTo(availableAmount) == 0) {
                        bf.setRelationState("N");
                    } else {
                        bf.setRelationState("B");
                    }
                    //修改可用金额、已用金额、关联状态
                    bankFlowDbService.updateByPrimaryKeySelective(bf);
                    //            log.info("预回款审核拒绝，修改银行流水记录的可用金额、已用金额、关联状态");
                }
                ReturnMoney rm = new ReturnMoney();
                rm.setReturnMoneyId(returnMoneyId);
                rm.setUpdateBy(curUserAccount.getAccountId());
                rm.setDelFlag(1);
                rm.setUpdateTm(now);
                //预回款审核拒绝，删除回款
                returnMoneyDbservice.updateReturnMoney(rm);
            }
        }else if(returnMoneyExamine.getFinanceExamineState() == 1) {//预回款审核通过后，先修改回款记录的回款状态为正常
            if(oldReturnMoney != null && oldReturnMoney.getCloseStatus() != null && oldReturnMoney.getCloseStatus() == 1){//不能通过审核：回款记录已封账
                return new DhResponse(ResponseCodeEnum.BANK_FLOW_EXAMINE_PASS_FAIL_HAS_CLOSE.getResponseCode());
            }
            ReturnMoney rm = new ReturnMoney();
            rm.setReturnMoneyId(returnMoneyId);
            rm.setUpdateBy(curUserAccount.getAccountId());
            rm.setUpdateTm(now);
            rm.setExamState(0);
            rm.setReturnStatus(1);
            rm.setDelFlag(0);
            returnMoneyDbservice.updateReturnMoney(rm);
//            log.info("预回款审核通过，修改回款记录的回款状态为正常");
        }

        //合同id
        String contractId = oldCustomerProductOrder.getContractId();
        //合同
        CustomerContract oldCustomerContract = customerContractDbService.selectContractById(contractId);

        //各表状态
        Map<String, String> status = bankFlowExamineService.getStatus(productOrderId, finishOrderProductNum, oldFinishOrderProduct, oldCustomerContract);

        //产品状态，0未回款 1退款 2部分回款 3已回款 4作废 5已兑换 6预回款
        String productStatus = status.get("productStatus");
        //订单状态，1:等待回款;2:已完成;3:作废;4:部分回款（回款维护）;5:预回款
        String orderStatus = status.get("orderStatus");
        //合同回款状态：0-未回款；1-已回款；3-部分回款；4-预回款
        String paymentStatus = status.get("paymentStatus");
        //合同状态:1-未生效；2-生效中；3-已结束；4-已作废；5-意外终止；6-挂起
        String contractStatus = status.get("contractStatus");

        //审核不管通不通过，都要修改回款记录表（若删除表则不需要改）、流水关联表（若删除表则不需要改）、finish表、订单表、合同表的回款状态从预回款改为未回款或部分回款或已回款（金额为0的情况）或正常

        //预回款审核不通过
        //删除回款记录，插入回款操作记录-----------------------代码在上面
        //修改银行流水的可用金额、已用金额、关联状态-----------------------代码在上面
        //修改订单完成的产品表的业绩金额、回款时间、产品状态（未回款、部分回款或预回款）
        //修改产品订单表的订单状态（未回款、部分回款或预回款），订单状态从2<已完成>到其他状态则卡作废，修改已回款金额合计
        //修改合同表到款时间、合同总回款金额、合同状态（订单状态为预回款，则合同也为预回款，订单状态若是2<已完成>，则合同状态是2<生效中>，否则合同状态是1<未生效>）
        if(returnMoneyExamine.getFinanceExamineState() == 2){
            if(StringUtils.isBlank(finishOrderProductNum)){
//                log.error("预回款审核时找不到产品号");
            }else{
                //产品最近回款记录
                ReturnMoney lastReturnMoney = returnMoneyDbservice.selectLastByFinishOrderProductNum(finishOrderProductNum);
                //产品最近到款时间
                Date arriveTime = null;
                if(lastReturnMoney != null){
                    arriveTime = lastReturnMoney.getArriveTime();
                }

                //订单完成的产品
                FinishOrderProduct fop = new FinishOrderProduct();

                //业绩换算比例
                BigDecimal performanceConversionRatio = new BigDecimal("0");
                if(oldFinishOrderProduct != null){
                    if(oldFinishOrderProduct.getPerformanceConversionRatio() != null){
                        performanceConversionRatio = oldFinishOrderProduct.getPerformanceConversionRatio();
                    }
                    if(oldFinishOrderProduct.getGradeMoney() != null ){
                        //业绩金额
                        BigDecimal gradeMoney = oldFinishOrderProduct.getGradeMoney();
                        if(gradeMoney != null && gradeMoney.compareTo(BigDecimal.ZERO) == 1){
                            //业绩金额-(回款金额*业绩换算比例)
                            gradeMoney = gradeMoney.subtract(arriveMoney.multiply(performanceConversionRatio));
                            fop.setGradeMoney(gradeMoney);
                        }
                    }
                }

                fop.setFinishOrderProductNum(finishOrderProductNum);
                fop.setProductStatus(productStatus);
                fop.setArriveTime(arriveTime);
                fop.setUpdatePeopleId(curUserAccount.getAccountId());
                fop.setUpdateTm(now);
                finishOrderProductDbService.updateArriveTimeAndOtherSelectiveInfo(fop);
//                log.info("预回款审核拒绝，修改订单完成的产品表的业绩金额、回款时间、产品状态（" + productStatus + "）");
            }

            if(StringUtils.isNotBlank(productOrderId)){
                //订单最近到款录入时间
                Date returnMoneyCreateTm = null;
                //订单最近回款记录
                ReturnMoney lastReturnMoney = returnMoneyDbservice.selectLastByOrderId(productOrderId, "create_tm desc");
                if(lastReturnMoney != null){
                    returnMoneyCreateTm = lastReturnMoney.getCreateTm();
                }
                CustomerProductOrder cpo = new CustomerProductOrder();

                //产品订单
                if(oldCustomerProductOrder != null){
                    //已回款金额合计
                    BigDecimal paidBackAmount = oldCustomerProductOrder.getPaidBackAmount()==null ? new BigDecimal("0") : oldCustomerProductOrder.getPaidBackAmount();
                    //已回款金额合计减到款金额
                    paidBackAmount = paidBackAmount.subtract(arriveMoney);
                    cpo.setPaidBackAmount(paidBackAmount);

                    if(StringUtils.isBlank(contractId)){
//                        log.error("流水审核时找不到合同id");
                    }else{
                        if(oldCustomerContract == null){
                            //                        log.error("预回款审核时找不到合同");
                        }else{
                            //合同总回款金额
                            BigDecimal contractTotalPaymentAmount = oldCustomerContract.getContractTotalPaymentAmount()==null ? new BigDecimal("0") : oldCustomerContract.getContractTotalPaymentAmount();
                            //合同总回款金额减到款金额
                            contractTotalPaymentAmount = contractTotalPaymentAmount.subtract(arriveMoney);

                            CustomerContract customerContract = new CustomerContract();
                            customerContract.setContractId(contractId);
                            customerContract.setContractStatus(contractStatus);
                            customerContract.setPaymentStatus(paymentStatus);
                            customerContract.setPaymentDate(returnMoneyCreateTm);
                            customerContract.setContractTotalPaymentAmount(contractTotalPaymentAmount);
                            customerContract.setUpdatePeopleId(curUserAccount.getAccountId());
                            customerContract.setUpdateTm(now);
                            customerContractDbService.updateArriveTimeAndOtherSelectiveInfo(customerContract);
                            //                        log.info("预回款审核拒绝，修改合同表到款时间、合同总回款金额、合同状态（" + contractStatus + "）、回款状态（" + paymentStatus + "）");
                        }
                    }
                }

                cpo.setProductOrderId(productOrderId);
                cpo.setUpdatePeopleId(curUserAccount.getAccountId());
                cpo.setUpdateTm(now);
                cpo.setOrderStatus(orderStatus);
//                if(arriveMoney.compareTo(new BigDecimal("0")) != 0) {//回款金额不等于0
//                    cpo.setOldOrder("-100");
//                }
                if(!"2".equals(orderStatus)){
                    cpo.setOldOrder("-100");
                }
                customerProductOrderDbService.updateOrderSelective(cpo);
                //            log.info("预回款审核拒绝，修改产品订单表的已回款金额合计及订单状态（" + orderStatus + "）");
            }

            if(StringUtils.isBlank(flowId)  || StringUtils.isBlank(productOrderId) || StringUtils.isBlank(returnMoneyId)){
//                log.error("预回款审核删除流水订单关联关系时，有空数据");
//                log.error("flowId:" + flowId + ", productOrderId:" + productOrderId + "returnMoneyId:" + returnMoneyId);
            }else{//删除流水订单关联关系
                BankOrder bo = new BankOrder();
                bo.setFlowId(flowId);
                bo.setOrderId(productOrderId);
                bo.setReturnMoneyId(returnMoneyId);
                bankOrderCustomMapper.delByFlowIdAndOrderIdAndReturnMoneyId(bo);
//                log.info("预回款审核拒绝，删除流水订单关联关系");
            }
        }else if(returnMoneyExamine.getFinanceExamineState() == 1){//预回款审核通过后，订单状态从其他状态到2<已完成>则发放会员卡，修改回款记录的回款状态为正常（代码在上面），插入回款操作记录
            if(StringUtils.isBlank(flowId)  || StringUtils.isBlank(productOrderId) || StringUtils.isBlank(returnMoneyId)){
//                log.error("预回款审核删除流水订单关联关系时，有空数据");
//                log.error("flowId:" + flowId + ", productOrderId:" + productOrderId + "returnMoneyId:" + returnMoneyId);
            }else{//修改流水订单关联表的订单回款状态
                BankOrder bo = new BankOrder();
                bo.setFlowId(flowId);
                bo.setOrderId(productOrderId);
                bo.setReturnMoneyId(returnMoneyId);
                bo.setReturnStatus(1);
                bankOrderCustomMapper.updateByFlowIdAndOrderIdAndReturnMoneyId(bo);
//                log.info("预回款审核通过，修改流水订单关联表的订单回款状态为正常");
            }

            if(oldFinishOrderProduct != null){
                //订单完成的产品
                FinishOrderProduct fop = new FinishOrderProduct();
                fop.setFinishOrderProductId(oldFinishOrderProduct.getFinishOrderProductId());
                fop.setProductStatus(productStatus);
                fop.setUpdatePeopleId(curUserAccount.getAccountId());
                fop.setUpdateTm(now);
                finishOrderProductDbService.updateFinishOrderProduct(fop);
//                log.info("预回款审核通过，修改订单完成的产品表的产品状态（" + productStatus + "）");
            }

            CustomerProductOrder cpo = new CustomerProductOrder();
            cpo.setProductOrderId(productOrderId);
            cpo.setUpdatePeopleId(curUserAccount.getAccountId());
            cpo.setUpdateTm(now);
            cpo.setOrderStatus(orderStatus);
//            if(!"2".equals(orderStatus)){
//                cpo.setOldOrder("-100");
//            }

            //订单状态从其他状态到2<已完成>，发放会员卡，修改订单完成时间
            if(oldCustomerProductOrder != null && !"2".equals(oldCustomerProductOrder.getOrderStatus()) && "2".equals(orderStatus)){
                cpo.setOrderCompleteTm(now);
                customerProductOrderDbService.updateOrderSelective(cpo);
//            log.info("预回款审核通过，修改产品订单表的订单状态（" + orderStatus + "）");
                try{
                    //发放会员卡
                    returnMoneyService.hairpin(productOrderId);
                }catch (ParseException e){
                    e.printStackTrace();
                }
                if(oldCustomerContract != null){
                    CustomerContract contract = new CustomerContract();
                    contract.setCustomerId(oldCustomerContract.getCustomerId());
                    //修改客户信息
                    returnMoneyService.updateCustomer(contract);
                }
            }else{
                customerProductOrderDbService.updateOrderSelective(cpo);
//            log.info("预回款审核通过，修改产品订单表的订单状态（" + orderStatus + "）");
            }

            CustomerContract customerContract = new CustomerContract();
            customerContract.setContractId(oldCustomerProductOrder.getContractId());
            customerContract.setContractStatus(contractStatus);
            customerContract.setPaymentStatus(paymentStatus);
            customerContract.setUpdatePeopleId(curUserAccount.getAccountId());
            customerContract.setUpdateTm(now);
            customerContractDbService.updateCustomerContract(customerContract);
//            log.info("预回款审核通过，修改合同表合同状态（" + contractStatus + "）、回款状态（" + paymentStatus + "）");
        }

        ReturnMoneyLog log = new ReturnMoneyLog();
        log.setReturnMoneyLogId(CommonUtils.getGUID());
        log.setFlowId(flowId);
        log.setReturnMoneyId(returnMoneyId);
        log.setCreatePeopleId(curUserAccount.getAccountId());
        log.setCreateTm(now);
        if(returnMoneyExamine.getFinanceExamineState() == 2){//审核拒绝
            log.setNewData("备注：预回款审核拒绝，删除回款记录，金额：" + arriveMoney);
            log.setOperatorType(2);  //操作类型 1修改 2删除 3退款 4关联 5调减
            returnMoneyExamine.setExamineState((short) 3);
        }else{//审核通过
            log.setNewData("备注：预回款审核通过，回款记录回款状态由" + ((oldReturnMoney.getReturnStatus()!=null && oldReturnMoney.getReturnStatus()==0) ? "预回款" : "正常") + "变为正常");
            log.setOperatorType(1);  //操作类型 1修改 2删除 3退款 4关联 5调减
            returnMoneyExamine.setExamineState((short) 2);
        }
        //插入回款操作记录
        returnMoneyLogDbService.addReturnMoneyLog(log);

        RmExamineRecord examineRecord = new RmExamineRecord();
        examineRecord.setRecordId(CommonUtils.getGUID());
        examineRecord.setExamineId(returnMoneyExamine.getExamineId());
        examineRecord.setCompanyId(curUserAccount.getCompanyId());
        examineRecord.setExaminePeopleId(curUserAccount.getAccountId());
        examineRecord.setExamineTime(now);
        if(oldExamine.getExamineState() == 0) {//客服正在审核
            examineRecord.setExaminePeopleType((short) 1);
            examineRecord.setExamineRemark(returnMoneyExamine.getCsExamineRemark());
            examineRecord.setExamineState(returnMoneyExamine.getCsExamineState());
        }else{
            examineRecord.setExaminePeopleType((short) 2);
            examineRecord.setExamineRemark(returnMoneyExamine.getFinanceExamineRemark());
            examineRecord.setExamineState(returnMoneyExamine.getFinanceExamineState());
        }
        //保存审核记录
        rmExamineRecordDbService.insertSelective(examineRecord);

        returnMoneyExamine.setLastRecordId(examineRecord.getRecordId());
        returnMoneyExamine.setFinanceExaminePeopleId(curUserAccount.getAccountId());
        returnMoneyExamine.setFinanceExamineTime(now);
        returnMoneyExamineDbService.updateByPrimaryKeySelective(returnMoneyExamine);

        //给业务人员发送站内信
        this.sendMsg(returnMoneyExamine.getExamineId(), oldExamine.getExamineState(), returnMoneyExamine.getFinanceExamineState(), oldCustomerProductOrder, oldReturnMoney);

        return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
    }

    @Override
    public DataResponse uploadMaterial(String examineId, MultipartFile file) {
        if(file == null){
            return new DhResponse(ResponseCodeEnum.RETURN_MONEY_EXAMINE_FILE_IS_NULL.getResponseCode());
        }

        ReturnMoneyExamine oldExamine = returnMoneyExamineDbService.selectByPrimaryKey(examineId);
        if(oldExamine == null || (oldExamine.getDeleteStatus() != null && oldExamine.getDeleteStatus() == 1)){
            return new DhResponse(ResponseCodeEnum.RETURN_MONEY_EXAMINE_NOT_EXIST.getResponseCode());
        }
        //总审核状态，0：客服正在审核，1：财务正在审核，2：审核通过，3：审核未通过
        if(oldExamine.getExamineState() == 2){
            return new DhResponse(ResponseCodeEnum.RETURN_MONEY_EXAMINE_UPLOAD_MATERIAL_FAIL_2.getResponseCode());
        }
        if(oldExamine.getExamineState() == 3){
            return new DhResponse(ResponseCodeEnum.RETURN_MONEY_EXAMINE_UPLOAD_MATERIAL_FAIL_3.getResponseCode());
        }
        if(oldExamine.getExamineState() == 0){
            if(oldExamine.getCsExamineState() == 0 && StringUtils.isNotBlank(oldExamine.getCsProveFileId())){
                return new DhResponse(ResponseCodeEnum.RETURN_MONEY_EXAMINE_UPLOAD_MATERIAL_FAIL_UPLOADED_CS_EXAMINING.getResponseCode());
            }
            if(oldExamine.getCsExamineState() != 3){
                return new DhResponse(ResponseCodeEnum.RETURN_MONEY_EXAMINE_UPLOAD_MATERIAL_FAIL_CS_EXAMINING.getResponseCode());
            }
        }
        if(oldExamine.getExamineState() == 1){
            if(oldExamine.getCsExamineState() == 0 && StringUtils.isNotBlank(oldExamine.getFinanceProveFileId())){
                return new DhResponse(ResponseCodeEnum.RETURN_MONEY_EXAMINE_UPLOAD_MATERIAL_FAIL_UPLOADED_FINANCE_EXAMINING.getResponseCode());
            }
            if(oldExamine.getFinanceExamineState() != 3){
                return new DhResponse(ResponseCodeEnum.RETURN_MONEY_EXAMINE_UPLOAD_MATERIAL_FAIL_FINANCE_EXAMINING.getResponseCode());
            }
        }

        // 文件名
        String fileName  = file.getOriginalFilename();
        // 文件类型
        String contentType = FilenameUtils.getExtension(fileName).toLowerCase();

        try {
            // 保存文件
            //file.transferTo(fileUpload);
            String fileSaveUrl = fastDFSClient.uploadFileWithMultipart(file);
            String accessUrl = "https://fastdfs.dcrm.cn/"+fileSaveUrl;
            String fileId = fileUploadService.insertFileUpload(fileName,fileSaveUrl,accessUrl,contentType);

            UserAccount curUserAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
            ReturnMoneyExamine examine = new ReturnMoneyExamine();
            examine.setExamineId(examineId);
            if(oldExamine.getExamineState() == 0){
                examine.setCsProveFileId(fileId);
                examine.setCsUploadPeopleId(curUserAccount.getAccountId());
                examine.setCsUploadTime(new Date());
            }else if(oldExamine.getExamineState() == 1){
                examine.setFinanceProveFileId(fileId);
                examine.setFinanceExamineState((short) -1);
                examine.setFinanceUploadPeopleId(curUserAccount.getAccountId());
                examine.setFinanceUploadTime(new Date());
            }
            //总审核状态改为客服正在审核
            examine.setExamineState((short) 0);
            //客服审核状态改为正在审核
            examine.setCsExamineState((short) 0);
//            //清空客服审核备注
            examine.setCsExamineRemark("");
            returnMoneyExamineDbService.updateByPrimaryKeySelective(examine);

        } catch (Exception e) {
            log.error("file upload error:", e);
        }
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
    }

    @Override
    public Map getDetails(String examineId) {
        ReturnMoneyExamineVO examine = returnMoneyExamineDbService.selectByExamineId(examineId);
        if(examine == null){
            return null;
        }

        Map data = new LinkedHashMap();

        data.put("examineId", examine.getExamineId());
        data.put("orderNumber", examine.getOrderNumber());
        data.put("flowCustomerName", examine.getFlowCustomerName());
        data.put("flowCreatePeopleName", examine.getFlowCreatePeopleName());
        data.put("transactionNo", examine.getTransactionNo());
        data.put("arriveMoney", examine.getArriveMoney()==null?null:examine.getArriveMoney().toString());
        data.put("orderCustomerName", examine.getOrderCustomerName());
        data.put("orderCreatePeopleName", examine.getOrderCreatePeopleName());
        data.put("csProveFile", examine.getCsProveFile());
        data.put("financeProveFile", examine.getFinanceProveFile());
        data.put("csExamineRemark", examine.getCsExamineRemark());
        data.put("financeExamineRemark", examine.getFinanceExamineRemark());
        data.put("examineState", examine.getExamineState());
        data.put("csExamineState", examine.getCsExamineState());
        data.put("financeExamineState", examine.getFinanceExamineState());

        //优先查正常产品
        FinanceProductOderInfoVO vo =customerProductOrderDbService.getFinanceProductOderInfo(examine.getProductOrderId(), null,1);
        if (Objects.isNull(vo)){
            vo =customerProductOrderDbService.getFinanceProductOderInfo(examine.getProductOrderId(), null,null);
        }
        if (Objects.nonNull(vo) && Objects.nonNull(vo.getOrderActualTotalAmount()) && Objects.nonNull(vo.getReturnMoneyAmount())){
            vo.setResidueMoneyAmount(vo.getOrderActualTotalAmount().subtract(vo.getReturnMoneyAmount()));
        }

        CustomerContractDetailVO customerContractDetailVO = customerContractService.selectCustomerContractVODetail(vo.getContractId());
        if (Objects.nonNull(customerContractDetailVO)){
            //隐藏客户信息
            customerContractDetailVO.setContactName(null);
            customerContractDetailVO.setContactDetails(null);
            customerContractDetailVO.setCustomerEmail(null);
        }

        data.put("productOrderId", examine.getProductOrderId());  //订单id

        if(customerContractDetailVO != null){
            data.put("contractId", customerContractDetailVO.getContractId());
            data.put("contractType", customerContractDetailVO.getContractType());  //合同类型
            if(customerContractDetailVO.getContractStartDate() != null){
                data.put("contractStartDate", DateUtil.formatDate(customerContractDetailVO.getContractStartDate()));  //合同开始时间
            }
            if(customerContractDetailVO.getContractEndDate() != null){
                data.put("contractEndDate", DateUtil.formatDate(customerContractDetailVO.getContractEndDate()));  //合同结束时间
            }
            data.put("contractNumber", customerContractDetailVO.getContractNumber());  //合同编号
        }

        if(vo != null){
            data.put("orderNumber", vo.getOrderNumber());  //订单编号
            data.put("orderStatus", vo.getOrderStatus());  //订单状态
            data.put("createPeopleName", vo.getCreatePeopleName());  //订单所有人
            data.put("orderCreateTm", vo.getCreateTm());  //订单创建时间
            data.put("orderCompanyName", vo.getCompanyName());  //订单所属分公司
            data.put("orderCustomerName2", vo.getCustomerName());  //订单客户名称
            data.put("orderActualTotalAmount", vo.getOrderActualTotalAmount()!=null ? vo.getOrderActualTotalAmount().toString() : "");  //订单总金额
            data.put("returnMoneyAmount", vo.getReturnMoneyAmount()!=null ? vo.getReturnMoneyAmount().toString() : "");  //订单当前回款
            data.put("residueMoneyAmount", vo.getResidueMoneyAmount()!=null ? vo.getResidueMoneyAmount().toString() : "");  //订单当前尾款
        }
        return data;
    }

    @Override
    public Boolean sendMsg(String examineId, Short examineState, Short newsDetailType, CustomerProductOrder customerProductOrder, ReturnMoneyVO oldReturnMoney) {
        //订单号
        String orderNumber = "";
        //合同id
        String contractId = "";
        //接收人id
        String accountId = null;
        //接收人公司id
        String companyId = null;
        if(customerProductOrder != null){
            orderNumber = customerProductOrder.getOrderNumber();
            contractId = customerProductOrder.getContractId();
            accountId = customerProductOrder.getCreatePeopleId();
        }
        UserAccount userAccount = userAccountDbService.selectUserAccountByAccountId(accountId);
        if(userAccount != null){
            companyId = userAccount.getCompanyId();
        }
        MessageAddQO qo = new MessageAddQO();
        qo.setTheme("回款审核");

        //站内信内容
        StringBuilder newsDetail = new StringBuilder();
        //回款编号
        String arriveNum = "";
        //到款金额
        BigDecimal arriveMoney = null;

        if(oldReturnMoney != null){
            arriveNum = oldReturnMoney.getArriveNum();
            arriveMoney = oldReturnMoney.getArriveMoney();
        }

        if(newsDetailType == 3){
            newsDetail.append("您有一条回款审核需要补充材料，订单号为：<a class=\"js-create-tab\" data-title=\"订单详情\" data-url=\"/front/orderManager/orderDetail?productOrderId=");
            newsDetail.append(customerProductOrder.getProductOrderId());
            newsDetail.append("&contractId=");
            newsDetail.append(contractId);
            newsDetail.append("\"><span>");
            newsDetail.append(orderNumber);
            newsDetail.append("</span>\n</a>\n，回款编号为：");
            newsDetail.append(arriveNum);
            newsDetail.append("，到款金额为：");
            newsDetail.append(arriveMoney);
            newsDetail.append("，请 <span class=\"supplementaryMaterial\" onclick=\"openSupplementaryMaterialModal(\'");
            newsDetail.append(examineId);
            newsDetail.append("')\">点击补充材料</span>，系统消息请勿回复。");
        }else{
            newsDetail.append("您有一条回款审核，订单号为：<a class=\"js-create-tab\" data-title=\"订单详情\" data-url=\"/front/orderManager/orderDetail?productOrderId=");
            newsDetail.append(customerProductOrder.getProductOrderId());
            newsDetail.append("&contractId=");
            newsDetail.append(contractId);
            newsDetail.append("\"><span>");
            newsDetail.append(orderNumber);
            newsDetail.append("</span>\n</a>\n，回款编号为：");
            newsDetail.append(arriveNum);
            newsDetail.append("，到款金额为：");
            newsDetail.append(arriveMoney);
            //站内信内容类型，1：审核通过，2：审核未通过，3：补充材料
            if(newsDetailType == 1){
                if(examineState == 0){
                    newsDetail.append("，客服审核结果为：<span style=\"color: #6b84ff;\">");
                    newsDetail.append("通过</span>，已移交至财务审核。系统消息请勿回复。");
                }else{
                    newsDetail.append("，财务审核结果为：<span style=\"color: #6b84ff;\">");
                    newsDetail.append("通过</span>，审核结束。系统消息请勿回复。");
                }
            }else if(newsDetailType == 2){
                if(examineState == 0){
                    newsDetail.append("，客服审核结果为：<span style=\"color: #ef087a;\">");
                    newsDetail.append("不通过</span>，已移交至财务审核。系统消息请勿回复。");
                }else{
                    newsDetail.append("，财务审核结果为：<span style=\"color: #ef087a;\">");
                    newsDetail.append("不通过</span>，审核结束。系统消息请勿回复。");
                }
            }
        }

//        examineState 审核状态，0：客服正在审核，1：财务正在审核
//        newsDetailType 站内信内容类型，1：审核通过，2：审核未通过，3：补充材料

        qo.setNewsDetail(newsDetail.toString());
        qo.setNewsType(2);
        qo.setAccountId(accountId);
        qo.setCompanyId(companyId);
        boolean rs = messageService.addMessage(qo);

        return rs;
    }
}